/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fleet.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.fee.entity.Receivable;
import com.jeeplus.modules.fleet.entity.*;
import com.jeeplus.modules.fleet.service.*;
import com.jeeplus.modules.infor.entity.LoadDetil;
import com.jeeplus.modules.infor.entity.ReDetil;
import com.jeeplus.modules.infor.entity.RentDetil;
import com.jeeplus.modules.infor.entity.RentPrice;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 自有车辆Controller
 * @author sld
 * @version 2017-11-23
 */
@Controller
@RequestMapping(value = "${adminPath}/fleet/vehicleInformation")
public class VehicleInformationController extends BaseController {

	@Autowired
	private VehicleInformationService vehicleInformationService;
	@Autowired
	private MotorcadeService motorcadeService;
	@Autowired
	private MotorcadeLogService motorcadeLogService;
	@Autowired
	private MotorcadeCostService motorcadeCostService;
	@Autowired
	private DepreciationService depreciationService;
	@Autowired
	private BudgetService budgetService;
	@Autowired
	private JdbcTemplate jdbc;


	@ModelAttribute
	public VehicleInformation get(@RequestParam(required=false) String id) {
		VehicleInformation entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = vehicleInformationService.get(id);
		}
		if (entity == null){
			entity = new VehicleInformation();
		}
		return entity;
	}
	
	/**
	 * 自有车辆列表页面
	 */
	@RequiresPermissions("fleet:vehicleInformation:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fleet/vehicleInformationList";
	}

	/**
	 * 车队收支明细
	 */
	@RequiresPermissions("fleet:vehicleInformation:list")
	@RequestMapping(value ="list1")
	public String list1() {
		return "modules/fleet/1/vehicleInformationList";
	}


	@ResponseBody
	@RequestMapping(value="cx")
	public  String cx1(String  min,String  max,String pro,String car) throws ParseException {
		if(min==null||max==null||min.equals("")||max.equals("")){
			return "false";
		}
		String sql="delete from fleet_budget ";

		jdbc.execute(sql);
		Calendar c = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=format.parse(min);
		Date ma=format.parse(max);
		Date mixx;
		Date maxx;

		List<Map<String,Object>> l=new ArrayList<>();

		while (i.getTime()<ma.getTime()) {
			mixx=i;
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;

			VehicleInformation v=new VehicleInformation();

			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				v.setProjectName(pro);
			}
			if(!UserUtils.getUseroffice().equals("总部")){
				v.setProjectName(UserUtils.getUseroffice());
			}
			if(car!=null&&!car.equals("")){
                 v.setLicense(car);
			}
			for(VehicleInformation vv:vehicleInformationService.findList(v)){
				Map<String,Object> map=new HashMap<String,Object>();
				//车队收入
				MotorcadeLog m=new MotorcadeLog();
				m.setProjectName(vv.getProjectName());
				map.put("date",format.format(mixx));
				map.put("car",vv.getLicense());
				m.setDate(mixx);
				m.setVehicleInformation(vv);
				List<MotorcadeLog> mos=motorcadeLogService.findList(m);
				int ts=0;
				double sr=0.0;
				for(MotorcadeLog mo:mos){
                   ts+=Integer.parseInt(mo.getCount());
                   sr+=Double.parseDouble(mo.getMoney());
				}
				map.put("ts",ts);
				map.put("sr",sr);
				//车队支出
				MotorcadeCost co=new MotorcadeCost();
				co.setProjectName(vv.getProjectName());
				co.setVehicleInformation(vv);
				co.setDate(mixx);
				List<MotorcadeCost> costs=motorcadeCostService.findList(co);
				double wxf=0.0;
				double zsf=0.0;
				double lqf=0.0;
				double jyf=0.0;
				double qt=0.0;
				double ltf=0.0;
				double fhf=0.0;
				double sh=0.0;
				for(MotorcadeCost mo:costs){
                   if(mo.getDisbursementType().equals("维修费")){
                         wxf+=Double.parseDouble(mo.getCost());
				   }
					if(mo.getDisbursementType().equals("加油费")){
						jyf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("住宿费")){
						zsf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("路桥费")){
						lqf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("轮胎费")){
						ltf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("防护费")){
						fhf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("产品损耗")){
						sh+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("其它费用")){
						qt+=Double.parseDouble(mo.getCost());
					}
				}
				map.put("wxf",wxf);
				map.put("zsf",zsf);
				map.put("lqf",lqf);
				map.put("jyf",jyf);
                map.put("qt",qt);
                map.put("lt",ltf);
                map.put("fh",fhf);
                map.put("sh",sh);
                //车辆折旧
				Depreciation d=new Depreciation();
				d.setPro(vv.getProjectName());
				d.setCar(vv);
				d.setMin(mixx);
				d.setMax(mixx);
				List<Depreciation> ll=depreciationService.findList(d);
				if(ll==null||ll.size()<1){
					map.put("zj",0);
				}else{
					map.put("zj",ll.get(0).getDepreciation());
				}
				l.add(map);
			}


		}
		for(Map<String,Object> m:l){
           Budget b=new Budget();
           b.setDate(m.get("date")+"");
			b.setCph(m.get("car")+"");
			b.setZts(m.get("ts")+"");
			b.setSr(m.get("sr")+"");
			b.setWxf(m.get("wxf")+"");
			b.setJyf(m.get("jyf")+"");
			b.setZsf(m.get("zsf")+"");
			b.setLqf(m.get("lqf")+"");
			b.setQtfy(m.get("qt")+"");
			b.setFhf(m.get("fh")+"");
			b.setLtf(m.get("lt")+"");
			b.setCpsh(m.get("sh")+"");
			b.setClzj(m.get("zj")+"");
			budgetService.save(b);
		}
		Gson g=new Gson();
		return g.toJson(l).toString();
	}

	public List<Map<String,Object>> cx(String  min,String  max,String pro,String car) throws ParseException {

		Calendar c = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=format.parse(min);
		Date ma=format.parse(max);
		Date mixx;
		Date maxx;

		List<Map<String,Object>> l=new ArrayList<>();
		int zts=0;
		double zsr=0.0;
		double zxlf=0.0;
		double zjyf=0.0;
		double zzsf = 0.0;
		double zlqf=0.0;
		double zqt=0.0;
		double zltf=0.0;
		double zfhf=0.0;
		double zsh=0.0;
		double zzj=0.0;

		while (i.getTime()<ma.getTime()) {
			mixx=i;
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;

			VehicleInformation v=new VehicleInformation();

			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				v.setProjectName(pro);
			}else if(!UserUtils.getUseroffice().equals("总部")){
				v.setProjectName(UserUtils.getUseroffice());
			}
			if(car!=null&&!car.equals("")){
				v.setLicense(car);
			}
			for(VehicleInformation vv:vehicleInformationService.findList(v)){
				Map<String,Object> map=new HashMap<String,Object>();
				//车队收入
				MotorcadeLog m=new MotorcadeLog();
				m.setProjectName(vv.getProjectName());
				map.put("date",format.format(mixx));
				map.put("car",vv.getLicense());
				m.setDate(mixx);
				m.setVehicleInformation(vv);
				List<MotorcadeLog> mos=motorcadeLogService.findList(m);
				int ts=0;
				double sr=0.0;
				for(MotorcadeLog mo:mos){
					ts+=Integer.parseInt(mo.getCount());
					sr+=Double.parseDouble(mo.getMoney());
					zts+=Integer.parseInt(mo.getCount());
					zsr+=Double.parseDouble(mo.getMoney());
				}
				map.put("ts",ts);
				map.put("sr",sr);
				//车队支出
				MotorcadeCost co=new MotorcadeCost();
				co.setProjectName(vv.getProjectName());
				co.setVehicleInformation(vv);
				co.setDate(mixx);
				List<MotorcadeCost> costs=motorcadeCostService.findList(co);
				double wxf=0.0;
				double zsf=0.0;
				double lqf=0.0;
				double jyf=0.0;
				double qt=0.0;
				double ltf=0.0;
				double fhf=0.0;
				double sh=0.0;
				for(MotorcadeCost mo:costs){
					if(mo.getDisbursementType().equals("维修费")){
						wxf+=Double.parseDouble(mo.getCost());
						zxlf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("加油费")){
						jyf+=Double.parseDouble(mo.getCost());
						zjyf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("住宿费")){
						zsf+=Double.parseDouble(mo.getCost());
						zzsf +=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("路桥费")){
						lqf+=Double.parseDouble(mo.getCost());
						zlqf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("轮胎费")){
						ltf+=Double.parseDouble(mo.getCost());
						zltf+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("防护费")){
						fhf+=Double.parseDouble(mo.getCost());
						zfhf +=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("产品损耗")){
						sh+=Double.parseDouble(mo.getCost());
						zsh+=Double.parseDouble(mo.getCost());
					}
					if(mo.getDisbursementType().equals("其它费用")){
						qt+=Double.parseDouble(mo.getCost());
						zqt+=Double.parseDouble(mo.getCost());
					}
				}
				map.put("wxf",wxf);
				map.put("zsf",zsf);
				map.put("lqf",lqf);
				map.put("jyf",jyf);
				map.put("qt",qt);
				map.put("lt",ltf);
				map.put("fh",fhf);
				map.put("sh",sh);
				//车辆折旧
				Depreciation d=new Depreciation();
				d.setPro(vv.getProjectName());
				d.setCar(vv);
				d.setMin(mixx);
				d.setMax(mixx);
				List<Depreciation> ll=depreciationService.findList(d);
				if(ll==null||ll.size()<1){
					map.put("zj",0);
				}else{
					map.put("zj",ll.get(0).getDepreciation());
					zzj+=Double.parseDouble(ll.get(0).getDepreciation());
				}
				l.add(map);
			}


		}
		Map<String ,Object> mm=new HashMap<String ,Object>();
		mm.put("ts",zts);
		mm.put("sr",zsr);
		mm.put("wxf",zxlf);
		mm.put("zsf", zzsf);
		mm.put("lqf",zlqf);
		mm.put("jyf",zjyf);
		mm.put("qt",zqt);
		mm.put("zj",zzj);
		mm.put("lt",zltf);
		mm.put("fh",zfhf);
		mm.put("sh",zsh);
		mm.put("car","");
		mm.put("size",l.size());
		l.add(mm);
		return  l;
	}

	@ResponseBody
	@RequestMapping(value="daochu")
	public  String dc(HttpServletResponse response,String  min,String  max,String pro,String car) throws ParseException {
		if(min==null||max==null||min.equals("")||max.equals("")){
			return "false";
		}
		List<Map<String,Object>> l= cx(min,max,pro,car);
		for(Map<String,Object> m:l){
			if(m.get("car").toString().equals("")){
				l.remove(m);
				break;
			}
		}
		Export e=new Export();
		e.exportveh(response,l);
		Gson g=new Gson();
		return "";
	}



		/**
	 * 自有车辆列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:vehicleInformation:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(VehicleInformation vehicleInformation, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){vehicleInformation.setProjectName(pro);}
		Page<VehicleInformation> page = vehicleInformationService.findPage(new Page<VehicleInformation>(request, response), vehicleInformation);
		return getBootstrapData(page);
	}
	/**
	 * 自有车辆列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "tc")
	public String tc(VehicleInformation vehicleInformation, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){vehicleInformation.setProjectName(pro);}
		List<VehicleInformation> list=vehicleInformationService.findList(vehicleInformation);
        Gson g=new Gson();
		return g.toJson(list).toString();
	}
	/**
	 * 查看，增加，编辑自有车辆表单页面
	 */
	@RequiresPermissions(value={"fleet:vehicleInformation:view","fleet:vehicleInformation:add","fleet:vehicleInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(VehicleInformation vehicleInformation, Model model) {
		model.addAttribute("vehicleInformation", vehicleInformation);
		return "modules/fleet/vehicleInformationForm";
	}

	/**
	 * 保存自有车辆
	 */
	@ResponseBody
	@RequiresPermissions(value={"fleet:vehicleInformation:add","fleet:vehicleInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(VehicleInformation vehicleInformation, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, vehicleInformation)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}

		vehicleInformation.setProjectName(motorcadeService.get(vehicleInformation.getMotorcade().getId()).getProject().getName());
		//新增或编辑表单保存
		vehicleInformationService.save(vehicleInformation);//保存
		j.setSuccess(true);
		j.setMsg("保存自有车辆成功");
		return j;
	}
	
	/**
	 * 删除自有车辆
	 */
	@ResponseBody
	@RequiresPermissions("fleet:vehicleInformation:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(VehicleInformation vehicleInformation, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		vehicleInformationService.delete(vehicleInformation);
		j.setMsg("删除自有车辆成功");
		return j;
	}
	
	/**
	 * 批量删除自有车辆
	 */
	@ResponseBody
	@RequiresPermissions("fleet:vehicleInformation:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			vehicleInformationService.delete(vehicleInformationService.get(id));
		}
		j.setMsg("删除自有车辆成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fleet:vehicleInformation:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(VehicleInformation vehicleInformation, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "自有车辆"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<VehicleInformation> page = vehicleInformationService.findPage(new Page<VehicleInformation>(request, response, -1), vehicleInformation);
    		new ExportExcel("自有车辆", VehicleInformation.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出自有车辆记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public VehicleInformation detail(String id) {
		return vehicleInformationService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fleet:vehicleInformation:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<VehicleInformation> list = ei.getDataList(VehicleInformation.class);
			for (VehicleInformation vehicleInformation : list){
				try{
					vehicleInformation.setProjectName(UserUtils.getUseroffice());
					vehicleInformationService.save(vehicleInformation);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条自有车辆记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条自有车辆记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入自有车辆失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/vehicleInformation/?repage";
    }
	
	/**
	 * 下载导入自有车辆数据模板
	 */
	@RequiresPermissions("fleet:vehicleInformation:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "自有车辆数据导入模板.xlsx";
    		List<VehicleInformation> list = Lists.newArrayList(); 
    		new ExportExcel("自有车辆数据", VehicleInformation.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/vehicleInformation/?repage";
    }
	

}